package com.example.com.transcribeeditpublish.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.com.transcribeeditpublish.PlayState;
import com.example.com.transcribeeditpublish.R;
import com.example.com.transcribeeditpublish.TCVideoEditerWrapper;
import com.example.com.transcribeeditpublish.databinding.ActivityVideoEditSimpleBinding;
import com.example.com.transcribeeditpublish.utils.DialogUtil;
import com.example.com.transcribeeditpublish.utils.FileUtils;
import com.example.com.transcribeeditpublish.utils.TCConstants;
import com.example.com.transcribeeditpublish.utils.TCEditerUtil;
import com.example.com.transcribeeditpublish.utils.TCUtils;
import com.example.com.transcribeeditpublish.views.RangeSliderViewContainer;
import com.example.com.transcribeeditpublish.views.VideoProgressController;
import com.example.com.transcribeeditpublish.views.VideoProgressView;
import com.example.com.transcribeeditpublish.views.VideoWorkProgressFragment;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.ugc.TXVideoEditConstants;
import com.tencent.ugc.TXVideoEditer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.utils.BaseUrlExternalStrageDir;
import me.goldze.mvvmhabit.utils.KLog;

import com.example.com.transcribeeditpublish.BR;
import com.tencent.ugc.TXVideoInfoReader;

public class VideoSimpleActivity extends BaseActivity<ActivityVideoEditSimpleBinding, BaseViewModel> implements TCVideoEditerWrapper.TXVideoPreviewListenerWrapper, TXVideoEditer.TXVideoGenerateListener {

    private Handler mMainHandler;
    private TCVideoEditerWrapper mEditerWrapper;
    private TXVideoEditer mTXVideoEditer;
    private long mVideoDuration;
    private String mvideoPath;
    private VideoProgressController mVideoProgressController;
    private boolean mLoadThumbnailSucc = false;
    private int mCurrentState = PlayState.STATE_NONE;
    private long mPreviewAtTime;
    private int mMaxDuration = 30 * 1000;
    //裁剪
    private VideoProgressController.VideoProgressSeekListener mVideoProgressSeekListener = new VideoProgressController.VideoProgressSeekListener() {
        @Override
        public void onVideoProgressSeek(long currentTimeMs) {
            KLog.e("Progress", currentTimeMs + "");
            previewAtTime(currentTimeMs);
        }

        @Override
        public void onVideoProgressSeekFinish(long currentTimeMs) {
            KLog.e("ProgressFinish", currentTimeMs + "");
            previewAtTime(currentTimeMs);
        }
    };
    private String mVideoOutputPath;
    private VideoWorkProgressFragment mWorkLoadingProgress;
    private String mCoverPath;
    private String delete;

    @Override
    public void onPreviewProgressWrapper(int timeMs) {
        // KLog.e("ProgressWrapper", "time");
        if (mCurrentState == PlayState.STATE_RESUME || mCurrentState == PlayState.STATE_PLAY) {
            mVideoProgressController.setCurrentTimeMs(timeMs);
        }

    }

    @Override
    public void onPreviewFinishedWrapper() {
        if (mCurrentState == PlayState.STATE_PREVIEW_AT_TIME) {
            return;
        }
        stopPlay();
        // 如果当前不是动态滤镜界面或者时间特效界面，那么会自动开始重复播放;
        startPlay(getCutterStartTime(), getCutterEndTime());

    }

    @Override
    public int initContentView() {
        return R.layout.activity_video_edit_simple;
    }

    @Override
    public int initVariableId() {
        return BR.entity;
    }

    @Override
    public BaseViewModel initViewModel() {
        return new BaseViewModel(this);
    }

    @Override
    public void initData() {
        super.initData();
        mvideoPath = getIntent().getStringExtra(TCConstants.VIDEO_EDITER_PATH);
        mCoverPath = getIntent().getStringExtra(TCConstants.VIDEO_RECORD_COVERPATH);


        mMainHandler = new Handler(Looper.getMainLooper());
        mEditerWrapper = TCVideoEditerWrapper.getInstance();
        mEditerWrapper.addTXVideoPreviewListenerWrapper(this);

        if (TextUtils.isEmpty(mvideoPath)) {
            Toast.makeText(this, "发生未知错误,路径不能为空", Toast.LENGTH_SHORT).show();
            finish();
        }

        mTXVideoEditer = mEditerWrapper.getEditer();
        if (mTXVideoEditer == null || mEditerWrapper.getTXVideoInfo() == null) {
            Toast.makeText(this, "状态异常，结束编辑", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mVideoDuration = mEditerWrapper.getTXVideoInfo().duration;
        mEditerWrapper.setCutterStartTime(0, mVideoDuration);
        getBinding().sumTime.setText("总时长: " + TCUtils.duration(mVideoDuration) + "s");
        getBinding().pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo();
            }
        });
        initVideoProgressLayout();
        initCutterSliderView();
        initPlayerLayout();

        getBinding().next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startGenerateVideo();
            }
        });

        getBinding().back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initVideoProgressLayout() {
        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);
        int screenWidth = point.x;
        getBinding().progressView.setViewWidth(screenWidth);
        List<Bitmap> thumbnailList = TCVideoEditerWrapper.getInstance().getAllThumbnails();
        getBinding().progressView.setThumbnailData();
        if (thumbnailList != null || thumbnailList.size() > 0) {
            getBinding().progressView.addAllThumbnail(thumbnailList);
        }


        mVideoProgressController = new VideoProgressController(mVideoDuration);
        mVideoProgressController.setVideoProgressView(getBinding().progressView);

        mVideoProgressController.setThumbnailPicListDisplayWidth(TCVideoEditerWrapper.mThumbnailCount);

        mTXVideoEditer.getThumbnail(TCVideoEditerWrapper.mThumbnailCount, 100, 100, false, new TXVideoEditer.TXThumbnailListener() {
            @Override
            public void onThumbnail(int index, long timeMs, final Bitmap bitmap) {
                TCVideoEditerWrapper.getInstance().addThumbnailBitmap(timeMs, bitmap);
                KLog.e("onThumbnail", "onThumbnail: index = " + index + ",timeMs:" + timeMs);
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        getBinding().progressView.addThumbnail(bitmap);
                    }
                });
//                if (index == TCVideoEditerWrapper.mThumbnailCount - 1) {
//                    mLoadThumbnailSucc = true;
//                }
            }
        });

        mVideoProgressController.setVideoProgressSeekListener(mVideoProgressSeekListener);
        mVideoProgressController.setVideoProgressDisplayWidth(screenWidth);
    }

    private void initCutterSliderView() {
        RangeSliderViewContainer mCutterRangeSliderView = new RangeSliderViewContainer(this);

        mCutterRangeSliderView.init(mVideoProgressController, 0, mVideoDuration, mVideoDuration);

        mVideoProgressController.addRangeSliderView(mCutterRangeSliderView);
        mCutterRangeSliderView.setDurationChangeListener(new RangeSliderViewContainer.OnDurationChangeListener() {
            @Override
            public void onDurationChange(long startTime, long endTime) {
                if (mTXVideoEditer != null) {
                    mTXVideoEditer.setCutFromTime(startTime, endTime);
                }
                String duration = TCUtils.duration(endTime - startTime);
                getBinding().sumTime.setText("总时长: " + duration + "s");
                TCVideoEditerWrapper.getInstance().setCutterStartTime(startTime, endTime);
            }
        });
    }

    private void initPlayerLayout() {
        TXVideoEditConstants.TXPreviewParam param = new TXVideoEditConstants.TXPreviewParam();
        param.videoView = getBinding().videoContianer;
        param.renderMode = TXVideoEditConstants.PREVIEW_RENDER_MODE_FILL_SCREEN;
        mTXVideoEditer.initWithPreview(param);
    }


    private long getCutterStartTime() {
        return mEditerWrapper.getCutterStartTime();
    }

    private long getCutterEndTime() {
        return mEditerWrapper.getCutterEndTime();
    }

    /**
     * 调用mTXVideoEditer.previewAtTime后，需要记录当前时间，下次播放时从当前时间开始
     * x
     *
     * @param timeMs
     */
    public void previewAtTime(long timeMs) {
        pausePlay();
        mTXVideoEditer.previewAtTime(timeMs);
        mPreviewAtTime = timeMs;
        mCurrentState = PlayState.STATE_PREVIEW_AT_TIME;
    }


    public void startPlay(long startTime, long endTime) {
        if (mCurrentState == PlayState.STATE_NONE || mCurrentState == PlayState.STATE_STOP || mCurrentState == PlayState.STATE_PREVIEW_AT_TIME) {
            mTXVideoEditer.startPlayFromTime(startTime, endTime);
            mCurrentState = PlayState.STATE_PLAY;
            getBinding().pause.setVisibility(View.GONE);
        }
    }

    public void resumePlay() {
        if (mCurrentState == PlayState.STATE_PAUSE) {
            mTXVideoEditer.resumePlay();
            mCurrentState = PlayState.STATE_RESUME;
        }
    }

    public void pausePlay() {
        if (mCurrentState == PlayState.STATE_RESUME || mCurrentState == PlayState.STATE_PLAY) {
            mTXVideoEditer.pausePlay();
            mCurrentState = PlayState.STATE_PAUSE;
            getBinding().pause.setVisibility(View.VISIBLE);
        }
    }

    public void stopPlay() {
        if (mCurrentState == PlayState.STATE_RESUME || mCurrentState == PlayState.STATE_PLAY ||
                mCurrentState == PlayState.STATE_PREVIEW_AT_TIME || mCurrentState == PlayState.STATE_PAUSE) {
            mTXVideoEditer.stopPlay();
            mCurrentState = PlayState.STATE_STOP;

        }
    }

    public void playVideo() {
        if (mCurrentState == PlayState.STATE_NONE || mCurrentState == PlayState.STATE_STOP) {
            KLog.e("Start", "getCutterStartTime=" + getCutterStartTime() + " , getCutterEndTime=" + getCutterEndTime());
            startPlay(getCutterStartTime(), getCutterEndTime());

        } else if ((mCurrentState == PlayState.STATE_RESUME || mCurrentState == PlayState.STATE_PLAY)) {
            pausePlay();
        } else if (mCurrentState == PlayState.STATE_PAUSE) {
            resumePlay();
        } else if (mCurrentState == PlayState.STATE_PREVIEW_AT_TIME) {
            if ((mPreviewAtTime >= getCutterEndTime() || mPreviewAtTime <= getCutterStartTime())) {
                startPlay(getCutterStartTime(), getCutterEndTime());
            } else if (!TCVideoEditerWrapper.getInstance().isReverse()) {
                startPlay(mPreviewAtTime, getCutterEndTime());
            } else {
                startPlay(getCutterStartTime(), mPreviewAtTime);
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mEditerWrapper.addTXVideoPreviewListenerWrapper(this);
        playVideo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlay();
        // 若当前处于生成状态，离开当前activity，直接停止生成
        if (mCurrentState == PlayState.STATE_GENERATE) {
            stopGenerate();
        }
        mEditerWrapper.removeTXVideoPreviewListenerWrapper(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mTXVideoEditer != null) {
            stopPlay();
            mTXVideoEditer.setVideoGenerateListener(null);
            //编辑完成后，销毁资源，避免影响处理下一个视频
            mTXVideoEditer.release();
            mTXVideoEditer = null;
        }
        // 清除对TXVideoEditer的引用以及相关配置
        mEditerWrapper.removeTXVideoPreviewListenerWrapper(this);
        mEditerWrapper.cleaThumbnails();
        mEditerWrapper.clear();
    }

    /**
     * =========================================视频生成相关==========================================
     */
    private void startGenerateVideo() {
        stopPlay(); // 停止播放
        mTXVideoEditer.cancel(); // 注意：生成时，停止输出缩略图

        // 处于生成状态
        mCurrentState = PlayState.STATE_GENERATE;
        // 防止
        getBinding().next.setEnabled(false);
        getBinding().next.setClickable(false);
        // 生成视频输出路径
        mVideoOutputPath = TCEditerUtil.generateVideoPath();

        if (mWorkLoadingProgress == null) {
            initWorkLoadingProgress();
        }
        mWorkLoadingProgress.setProgress(0);
        mWorkLoadingProgress.setCancelable(false);
        mWorkLoadingProgress.show(getSupportFragmentManager(), "progress_dialog");

        // 添加片尾水印
        //   addTailWaterMark();

        mTXVideoEditer.setCutFromTime(getCutterStartTime(), getCutterEndTime());
        mTXVideoEditer.setVideoGenerateListener(this);

//        if (mCustomBitrate != 0) { // 是否自定义码率
//            mTXVideoEditer.setVideoBitrate(mCustomBitrate);
//        }

        mTXVideoEditer.generateVideo(TXVideoEditConstants.VIDEO_COMPRESSED_720P, mVideoOutputPath);

    }

    private void stopGenerate() {
        if (mWorkLoadingProgress != null) {
            mWorkLoadingProgress.setProgress(0);
            mWorkLoadingProgress.dismiss();
        }
        if (mCurrentState == PlayState.STATE_GENERATE) {
            getBinding().next.setEnabled(true);
            getBinding().next.setClickable(true);
            Toast.makeText(this, "取消视频生成", Toast.LENGTH_SHORT).show();
            mCurrentState = PlayState.STATE_NONE;
            if (mTXVideoEditer != null) {
                mTXVideoEditer.cancel();
            }
        }
    }

    @Override
    public void onGenerateProgress(float progress) {
        mWorkLoadingProgress.setProgress((int) (progress * 100));
    }

    @Override
    public void onGenerateComplete(TXVideoEditConstants.TXGenerateResult result) {
        if (result.retCode == TXVideoEditConstants.GENERATE_RESULT_OK) {
            // 生成成功
            createThumbFile(result);
        } else {
            Toast.makeText(this, result.descMsg, Toast.LENGTH_SHORT).show();
            mWorkLoadingProgress.dismiss();
        }
        getBinding().next.setEnabled(true);
        getBinding().next.setClickable(true);
        mCurrentState = PlayState.STATE_NONE;
    }

    /**
     * 创建缩略图，并跳转至视频预览的Activity
     */
    private void createThumbFile(final TXVideoEditConstants.TXGenerateResult result) {

        AsyncTask<Void, String, String> task = new AsyncTask<Void, String, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                File outputVideo = new File(mVideoOutputPath);
                if (!outputVideo.exists())
                    return null;
                Bitmap bitmap = TXVideoInfoReader.getInstance().getSampleImage(0, mVideoOutputPath);
                if (bitmap == null)
                    return null;
                String folder = BaseUrlExternalStrageDir.getBaseUrl() + File.separator + "video";

                File appDir = new File(folder);
                if (!appDir.exists()) {
                    appDir.mkdirs();
                }

                String fileName = "thumbnail" + ".jpg";
                File file = new File(appDir, fileName);
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return file.getAbsolutePath();
            }

            @Override
            protected void onPostExecute(String s) {
                // FileUtils.deleteFile(mvideoPath);
                // FileUtils.deleteFile(mCoverPath);
                startPreviewActivity(result, s);
            }
        };
        task.execute();
    }

    private void startPreviewActivity(TXVideoEditConstants.TXGenerateResult result, String thumbPath) {
        mWorkLoadingProgress.dismiss();
        Intent intent = new Intent(this, PreviewActvity.class);
        // intent.putExtra(TCConstants.VIDEO_RECORD_TYPE, TCConstants.VIDEO_RECORD_TYPE_EDIT);
        intent.putExtra(TCConstants.VIDEO_RECORD_VIDEPATH, mVideoOutputPath);
        if (thumbPath != null)
            intent.putExtra(TCConstants.VIDEO_RECORD_COVERPATH, thumbPath);
        intent.putExtra(TCConstants.VIDEO_RECORD_DURATION, getCutterEndTime() - getCutterStartTime());
        startActivity(intent);
        // finish();
    }

    /**
     * ==========================================进度条==========================================
     */
    private void initWorkLoadingProgress() {
        if (mWorkLoadingProgress == null) {
            mWorkLoadingProgress = new VideoWorkProgressFragment();
        }
        mWorkLoadingProgress.setProgress(0);
    }
}
